//
//  AppDelegate.m
//  翻转效果
//
//  Created by Lucifer on 15-5-18.
//  Copyright (c) 2015年 xuxzhou. All rights reserved.
//

#import "AppDelegate.h"
#import "UIImage+Creation.h"
#import "UIColor+Helper.h"
#import "OneViewController.h"
#import "TwoViewController.h"
#import "ThreeViewController.h"
#import "drawerViewController.h"
#import "rightDrawerViewController.h"
#import "EaseMob.h"
#import "APService.h"
#define item_image(_name_) [[UIImage imageNamed:_name_] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]

@interface AppDelegate ()<EMChatManagerDelegate>
@property (nonatomic, strong) UIWindow * statusWindow;
@property (nonatomic, strong) UILabel * statusLabel;
- (void) dismissStatus;

@end

@implementation AppDelegate
+ (AppDelegate*)shareApplication
{
    return (AppDelegate*)[UIApplication sharedApplication].delegate;
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
   

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];

   
//    环信
    [self registerEaseMob:application didFinishLaunchingWithOptions:launchOptions];
   
//    极光
    [self registerAPService:application didFinishLaunchingWithOptions:launchOptions];
    [self showHomeView];
    return YES;
}

#pragma mark -- 极光推送
-(void)registerAPService:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Required
    
    //可以添加自定义categories

    [APService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                   UIUserNotificationTypeSound |
                                                   UIUserNotificationTypeAlert)
                                       categories:nil];
    
    /*
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [APService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                       UIUserNotificationTypeSound |
                                                       UIUserNotificationTypeAlert)
                                           categories:nil];
    } else {
        //categories 必须为nil
        [APService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                       UIRemoteNotificationTypeSound |
                                                       UIRemoteNotificationTypeAlert)
                                           categories:nil];
    }
    */
    // Required
    
    //设置什么tag值？
    //    APService setTags:<#(NSSet *)#> alias:@"xuxuzhou" callbackSelector:<#(SEL)#> object:<#(id)#>
    
    [APService setupWithOption:launchOptions];
    
    //自定义消息接受
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    // Required
    [APService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    // 取得 APNs 标准信息内容
    NSDictionary *aps = [userInfo valueForKey:@"aps"];
    NSString *content = [aps valueForKey:@"alert"]; //推送显示的内容
    NSInteger badge = [[aps valueForKey:@"badge"] integerValue]; //badge数量
    NSString *sound = [aps valueForKey:@"sound"]; //播放的声音
    // 取得自定义字段内容
    NSString *customizeField1 = [userInfo valueForKey:@"customizeField1"]; //自定义参数，key是自己定义的
    NSLog(@"content =[%@], badge=[%ld], sound=[%@], customize field  =[%@]",content,badge,sound,customizeField1);

    // Required
    [APService handleRemoteNotification:userInfo];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    NSLog(@"this is iOS7 Remote Notification");
    // 取得 APNs 标准信息内容
    NSDictionary *aps = [userInfo valueForKey:@"aps"];
    NSString *content = [aps valueForKey:@"alert"]; //推送显示的内容
    NSInteger badge = [[aps valueForKey:@"badge"] integerValue]; //badge数量
    NSString *sound = [aps valueForKey:@"sound"]; //播放的声音
    // 取得自定义字段内容
    NSString *customizeField1 = [userInfo valueForKey:@"customizeField1"]; //自定义参数，key是自己定义的
    NSLog(@"content =[%@], badge=[%ld], sound=[%@], customize field  =[%@]",content,badge,sound,customizeField1);
    // IOS 7 Support Required
    [APService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)networkDidReceiveMessage:(NSNotification *)notification {
    NSDictionary * userInfo = [notification userInfo];
    NSString *content = [userInfo valueForKey:@"content"];
    NSDictionary *extras = [userInfo valueForKey:@"extras"];
    NSString *customizeField1 = [extras valueForKey:@"customizeField1"]; //自定义参数，key是自己定义的
    NSLog(@"%@%@%@",userInfo,content,customizeField1);
    [APService handleRemoteNotification:userInfo];

}

#pragma mark -- 环信EaseMob
-(void)registerEaseMob:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    //registerSDKWithAppKey:注册的appKey，详细见下面注释。
    //apnsCertName:推送证书名(不需要加后缀)，详细见下面注释。
    [[EaseMob sharedInstance] registerSDKWithAppKey:@"zhouyingxuself#myselftest" apnsCertName:@"myselfTestDev"];
    [[EaseMob sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
    //registerSDKWithAppKey: 区别app的标识，
    //apnsCertName: iOS中推送证书名称。
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
    
    [[EaseMob sharedInstance].chatManager asyncRegisterNewAccount:@"xuxuSelf" password:@"111111" withCompletion:^(NSString *username, NSString *password, EMError *error) {
        if (!error) {
            NSLog(@"注册成功");
        }
    } onQueue:nil];
    [[EaseMob sharedInstance].chatManager asyncRegisterNewAccount:@"xuxuSelf" password:@"111111"];


}
/*!
 @method
 @brief 注册新用户后的回调
 @discussion
 @result
 */
- (void)didRegisterNewAccount:(NSString *)username
                     password:(NSString *)password
                        error:(EMError *)error{
    NSLog(@"%@ %@ ",username,password);
    
}

#pragma mark --

- (void)showHomeView
{
    self.onePageNav = ({
        UIViewController *mainpageViewController = [[OneViewController alloc] init];
        UITabBarItem *item = [[UITabBarItem alloc] initWithTitle:@""
                                                           image:item_image(@"main_normol")
                                                   selectedImage:item_image(@"main_selected")];
        
        UINavigationController *mainpageViewNav = [[UINavigationController alloc] initWithRootViewController:mainpageViewController];
        [mainpageViewNav.navigationBar setTitleTextAttributes:@{
                                                         NSForegroundColorAttributeName : [UIColor whiteColor],
                                                         NSFontAttributeName : [UIFont systemFontOfSize:17.0f]
                                                         }];
        [mainpageViewNav.navigationBar setBackgroundImage:[UIImage imageWithColor:[UIColor mainColor]] forBarMetrics:UIBarMetricsDefault];
        [mainpageViewNav.navigationBar setShadowImage:[[UIImage alloc] init]];
        item.imageInsets = UIEdgeInsetsMake(5, 0, -5, 0);
        mainpageViewNav.tabBarItem = item;
        mainpageViewNav;
    });
    
    self.twoPageNav = ({
        UIViewController *circlePageViewController = [[TwoViewController alloc] init];
        UITabBarItem *item = [[UITabBarItem alloc] initWithTitle:@""
                                                           image:item_image(@"talk_normol")
                                                   selectedImage:item_image(@"talk_selected")];
        UINavigationController *circleViewNav = [[UINavigationController alloc] initWithRootViewController:circlePageViewController];
        [circleViewNav.navigationBar setTitleTextAttributes:@{
                                                                NSForegroundColorAttributeName : [UIColor whiteColor],
                                                                NSFontAttributeName : [UIFont systemFontOfSize:17.0f]
                                                                }];
        [circleViewNav.navigationBar setBackgroundImage:[UIImage imageWithColor:[UIColor mainColor]] forBarMetrics:UIBarMetricsDefault];
        [circleViewNav.navigationBar setShadowImage:[[UIImage alloc] init]];
        item.imageInsets = UIEdgeInsetsMake(5, 0, -5, 0);
        circleViewNav.tabBarItem = item;
        circleViewNav;
    });
    
    self.threePageNav = ({
        UIViewController *personagePageViewController = [[ThreeViewController alloc] init];
        UITabBarItem *item = [[UITabBarItem alloc] initWithTitle:@""
                                                           image:item_image(@"user_normol")
                                                   selectedImage:item_image(@"user_selected")];
        UINavigationController *personageViewNav = [[UINavigationController alloc] initWithRootViewController:personagePageViewController];
        [personageViewNav.navigationBar setTitleTextAttributes:@{
                                                                NSForegroundColorAttributeName : [UIColor whiteColor],
                                                                NSFontAttributeName : [UIFont systemFontOfSize:17.0f]
                                                                }];
        [personageViewNav.navigationBar setBackgroundImage:[UIImage imageWithColor:[UIColor mainColor]] forBarMetrics:UIBarMetricsDefault];
        [personageViewNav.navigationBar setShadowImage:[[UIImage alloc] init]];
        item.imageInsets = UIEdgeInsetsMake(5, 0, -5, 0);
        personageViewNav.tabBarItem = item;
        personageViewNav;
    });
    
    self.tabBarController = [[UITabBarController alloc] init];
    self.tabBarController.tabBar.tintColor = [UIColor colorWithRed: 27 / 255.0 green: 129 / 255.0 blue: 172 / 255.0 alpha: 1];
    self.tabBarController.tabBar.backgroundColor=[UIColor mainColor];
    [self.tabBarController setViewControllers:@[ self.onePageNav,
                                                 self.twoPageNav,
                                                 self.threePageNav
                                                 ]];
    self.mainNavigationController = [[UINavigationController alloc] initWithRootViewController:self.tabBarController];
    self.mainNavigationController.delegate = self;
    self.mainNavigationController.navigationBarHidden = YES;
    self.sideMenu=[[RESideMenu alloc]initWithContentViewController:_mainNavigationController leftMenuViewController:[[drawerViewController alloc]init] rightMenuViewController:[[rightDrawerViewController alloc]init]];
    
    self.window.rootViewController = self.sideMenu;
}



/**
 * @brief 在状态栏显示 一些Log
 *
 * @param string 需要显示的内容
 * @param duration  需要显示多长时间
 */
+ (void) showStatusWithText:(NSString *) string duration:(NSTimeInterval) duration {
    
    AppDelegate * delegate = (AppDelegate *) [UIApplication sharedApplication].delegate;
    
    delegate.statusLabel.text = string;
    [delegate.statusLabel sizeToFit];
    CGRect rect = [UIApplication sharedApplication].statusBarFrame;
    CGFloat width = delegate.statusLabel.frame.size.width;
    CGFloat height = rect.size.height;
    rect.origin.x = rect.size.width - width - 5;
    rect.size.width = width;
    delegate.statusWindow.frame = rect;
    delegate.statusLabel.frame = CGRectMake(0, 0, width, height);
    
    if (duration < 1.0) {
        duration = 1.0;
    }
    if (duration > 4.0) {
        duration = 4.0;
    }
    [delegate performSelector:@selector(dismissStatus) withObject:nil afterDelay:duration];
}

/**
 * @brief 干掉状态栏文字
 */
- (void) dismissStatus {
    CGRect rect = self.statusWindow.frame;
    rect.origin.y -= rect.size.height;
    [UIView animateWithDuration:0.5 animations:^{
        self.statusWindow.frame = rect;
    }];
}



// App进入后台
- (void)applicationDidEnterBackground:(UIApplication *)application
{
    [[EaseMob sharedInstance] applicationDidEnterBackground:application];
}

// App将要从后台返回
- (void)applicationWillEnterForeground:(UIApplication *)application
{
    [[EaseMob sharedInstance] applicationWillEnterForeground:application];
}

// 申请处理时间
- (void)applicationWillTerminate:(UIApplication *)application
{
    [[EaseMob sharedInstance] applicationWillTerminate:application];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


@end
